package yur.wedding.modules.sys.service.impl;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Service;


import java.net.SocketException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.springframework.transaction.annotation.Transactional;
import yur.wedding.common.utils.PdfUtilsTest;
import yur.wedding.common.utils.Query;

import yur.wedding.modules.sys.Vo.documentVo;
import yur.wedding.modules.sys.dao.SysDocumentDao;
import yur.wedding.modules.sys.entity.*;
import yur.wedding.modules.sys.service.*;
import yur.wedding.utils.HttpContextUtils;
import yur.wedding.utils.IPUtils;
import yur.wedding.utils.PageUtils;
import yur.wedding.utils.R;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;


@Service("sysDocumentService")
public class SysDocumentServiceImpl extends ServiceImpl<SysDocumentDao, SysDocumentEntity> implements SysDocumentService {


    @Resource
    SysUserServiceImpl service;

    @Resource
    SysDocumentDirectoryrightsService sysDocumentDirectoryrightsService;

    @Resource
    SysDocshareService sysDocshareService;

    @Resource
    SysDocumentDocsubcategoryService sysDocumentDocsubcategoryService;
    @Resource
    SysUserService sysUserService;


    @Resource
    SysDocdetailLogService sysDocdetailLogService;

    @Override

    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SysDocumentEntity> page = this.page(
                new Query<SysDocumentEntity>().getPage(params),
                new QueryWrapper<SysDocumentEntity>()
        );
        for (SysDocumentEntity list : page.getRecords()) {
            SysUserEntity byId1 = sysUserService.getById(list.getCreatorid());
            list.setCreatorName(byId1.getLastName());

        }
        return new PageUtils(page);

    }


    /**
     * 2.并且生成附件
     * 1.添加文档
     * 3.获取该目录权限 为文档添加权限
     *
     * @param sysDocument
     * @return
     */
    @Override
    @Transactional
    public R savePicture(SysDocumentEntity sysDocument, Long useriD) {
        SysUserEntity byId = service.getById(useriD);

        PdfUtilsTest utilsTest = new PdfUtilsTest();
        String pdf = utilsTest.createdPdfByItextHtml(sysDocument.getContent(), byId.getLastName() + "-" + sysDocument.getHeadline());
        sysDocument.setAccessoryurl(pdf);//保存附件地址
        sysDocument.setCreatorid(useriD);//保存当前创建人
        sysDocument.setCreateDate(new Date());//获取当前时间
        //生成编号
        DateTimeFormatter ofPattern = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
        String localDate = LocalDateTime.now().format(ofPattern);
        String orderNum = localDate + useriD;

        sysDocument.setDoccode(orderNum);
        SysDocumentDocsubcategoryEntity byId1 = sysDocumentDocsubcategoryService.getById(sysDocument.getParentId());
        /**
         * 目录中   0 待发布 1发布
         *
         * 文档中   1:正常   2:待发布
         */
        int flag = (byId1.getDelFlagzt() == 1 ? 1 : 2);
        sysDocument.setDelFlag(flag);//保存 是否发布  0 待发布 1发布


        baseMapper.insert(sysDocument);//添加成功

        //获取目录权限 添加到文档权限
        PageUtils pageUtils = sysDocumentDirectoryrightsService.documentDirectoryrightslist(sysDocument.getParentId(), new HashMap<>());

        for (Object object : pageUtils.getList()) {//将object  用json 转换为实体类
            JSONObject jsonData = (JSONObject) JSONObject.toJSON(object);
            SysDocumentDirectoryrightsEntity company = JSONObject.toJavaObject(JSONObject.parseObject(JSONObject.toJSONString(jsonData)), SysDocumentDirectoryrightsEntity.class);
            SysDocshareEntity docshareEntity = new SysDocshareEntity();
            docshareEntity.setCreateDate(new Date());//创建时间
            docshareEntity.setDocid(sysDocument.getDocumentId());//文档id
            docshareEntity.setSharelevel(company.getSharelevel());
            docshareEntity.setSharetype(company.getSharetype());
            docshareEntity.setUserid(company.getUserid());
            docshareEntity.setDepartmentid(company.getDepartmentid());
            docshareEntity.setRoleid(company.getRoleid());
            docshareEntity.setForalluser(company.getForalluser());
            docshareEntity.setDownloadlevel(company.getDownloadlevel());
            sysDocshareService.save(docshareEntity);
        }
        //默认添加创建人所有权限
        SysDocshareEntity creatorDocshareEntity = new SysDocshareEntity();
        creatorDocshareEntity.setCreateDate(new Date());//创建时间
        creatorDocshareEntity.setDocid(sysDocument.getDocumentId());//文档id
        creatorDocshareEntity.setSharelevel(2);//共享级别(	1：查看，2：编辑)
        creatorDocshareEntity.setSharetype(1);
        creatorDocshareEntity.setUserid(useriD);
        creatorDocshareEntity.setDepartmentid(0L);
        creatorDocshareEntity.setRoleid(0L);
        creatorDocshareEntity.setForalluser(0);
        creatorDocshareEntity.setDownloadlevel(1);
        sysDocshareService.save(creatorDocshareEntity);


        return R.ok().put("documentId", sysDocument.getDocumentId());
    }


    @Override
    public documentVo info(String documentId) {
        net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(documentId);
        String dbgyId1 = (String) jsonObject.get("documentId");
        Long dbgyId = Long.valueOf(dbgyId1);
        documentVo vo = new documentVo();
        //1.添加文档信息
        SysDocumentEntity documentEntity = baseMapper.selectById(dbgyId);
        vo.setSysDocumentEntity(documentEntity);
        //2添加目录名称
        SysDocumentDocsubcategoryEntity byId = sysDocumentDocsubcategoryService.getById(documentEntity.getParentId());
        //递归查询名称 报告父类名称
        String docs = recursionDocs(byId.getCategoryname(), byId);
        vo.setParentName(docs);
        //3.添加文档所有者名称
        SysUserEntity byId1 = sysUserService.getById(documentEntity.getCreatorid());
        vo.setDocumentName(byId1.getLastName());


        //3.添加文档日志信息
        //List<SysDocdetailLogEntity> list = docdetailLogService.getLogList(dbgyId);
        //vo.setLogEntityList(list);
        //4.添加文档权限信息
        // List<SysDocshareEntity> list1=sysDocshareService.getShareList(dbgyId);
        // vo.setShareEntityList(list1);

        //添加查看日志
        Long userId = ((SysUserEntity) SecurityUtils.getSubject().getPrincipal()).getUserId();
        SysDocdetailLogEntity logEntity = sysDocdetailLogService.userInfolog(dbgyId, userId, 0);
        if (logEntity == null) {
            SysDocdetailLogEntity entity = new SysDocdetailLogEntity();
            entity.setDocid(dbgyId);
            entity.setOperateuserid(userId);
            entity.setOperatetype(0);
            entity.setCreateDate(new Date());
            //获取request
            HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
            //设置IP地址
            entity.setIp(IPUtils.getLocalIp4Address().get().toString().replaceAll("/", ""));
            sysDocdetailLogService.save(entity);
        }


        return vo;
    }

    /**
     * 查看文档接口
     * * 1.管理员查看   模糊查询+条件查询
     */
    @Override
    public PageUtils queryPageAdministrator(Map<String, Object> params) {
        System.out.println("模糊查询+条件查询");
        String wdbh = (String) params.get("wdbh");
        String wdbt = (String) params.get("wdbt");
        String username = (String) params.get("username");

        String cjrq = (String) params.get("cjrq");
        String jsrq = (String) params.get("jsrq");

        String mlid = (String) params.get("mlid");
        String wdzt = (String) params.get("wdzt");

        QueryWrapper<SysDocumentEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(mlid), "parent_id", mlid);//目录id
        wrapper.eq(StringUtils.isNotBlank(wdzt), "del_flag", wdzt);
        wrapper.like(StringUtils.isNotBlank(wdbh), "doccode", wdbh);
        wrapper.like(StringUtils.isNotBlank(wdbt), "headline", wdbt);
        wrapper.le(StringUtils.isNotBlank(cjrq), "create_date", jsrq);
        wrapper.ge(StringUtils.isNotBlank(jsrq), "create_date", cjrq);

        wrapper.ge(StringUtils.isNotBlank(jsrq), "create_date", cjrq);

        IPage<SysDocumentEntity> page = this.page(
                new Query<SysDocumentEntity>().getPage(params), wrapper
        );

        for (SysDocumentEntity list : page.getRecords()) {
            SysUserEntity byId1 = sysUserService.getById(list.getCreatorid());
            list.setCreatorName(byId1.getLastName());

        }

        return new PageUtils(page);
    }

    /**
     * 查看文档  接口
     * 2.其他人员查看   普通查询
     *
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageholDer(Map<String, Object> params, Long userid) {

        //TODO 后续可保存致缓存
        //查询文档权限


        IPage<SysDocumentEntity> page = this.page(
                new Query<SysDocumentEntity>().getPage(params),
                new QueryWrapper<SysDocumentEntity>().in("document_id", filtRationList(userid))
        );
        for (SysDocumentEntity list : page.getRecords()) {
            SysUserEntity byId1 = sysUserService.getById(list.getCreatorid());
            list.setCreatorName(byId1.getLastName());

        }
        return new PageUtils(page);
    }

    /**
     * 查看文档  接口
     * 2.其他人员查看   模糊查询+条件查询
     *
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageholDeristrator(Map<String, Object> params, Long userid) {
        String wdbh = (String) params.get("wdbh");
        String wdbt = (String) params.get("wdbt");
        String cjrq = (String) params.get("cjrq");
        String jsrq = (String) params.get("jsrq");
        String mlid = (String) params.get("mlid");
        String wdzt = (String) params.get("wdzt");
        QueryWrapper<SysDocumentEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(mlid), "parent_id", mlid);//目录id
        wrapper.eq(StringUtils.isNotBlank(wdzt), "del_fiag", wdzt);//文档状态
        wrapper.like(StringUtils.isNotBlank(wdbh), "doccode", wdbh);
        wrapper.like(StringUtils.isNotBlank(wdbt), "headline", wdbt);
        wrapper.le(StringUtils.isNotBlank(cjrq), "create_date", jsrq);
        wrapper.ge(StringUtils.isNotBlank(jsrq), "create_date", cjrq);

        wrapper.in("document_id", filtRationList(userid));
        IPage<SysDocumentEntity> page = this.page(
                new Query<SysDocumentEntity>().getPage(params), wrapper
        );

        for (SysDocumentEntity list : page.getRecords()) {
            SysUserEntity byId1 = sysUserService.getById(list.getCreatorid());
            list.setCreatorName(byId1.getLastName());

        }

        return new PageUtils(page);
    }

    /**
     * 通过目录id查询 文档
     *
     * @param parentId
     * @return
     */
    @Override
    public List<SysDocumentEntity> queryList(Integer parentId) {


        return baseMapper.queryList(parentId);
    }

    /**
     * 发布  作废  重新发布
     *
     * @param documentIds
     * @param state
     * @return
     */
    @Override
    public Boolean updateDoc(Long[] documentIds, String state) {


        if ("publishDoc".equals(state)) {//发布
            baseMapper.publishDoc(documentIds);
        } else if ("cancelDoc".equals(state)) {//作废
            baseMapper.cancelDoc(documentIds);
        } else {
            return false;
        }


        return true;
    }

    /**
     * 文档删除
     * 1.删除文档
     * 2.删除文档权限
     * 3.删除日志
     *
     * @param documentIds
     * @return
     */
    @Override
    @Transactional
    public Boolean deleteDoc(Long[] documentIds) {

        for (Long ln : documentIds) {

        }

        return true;
    }


    /**
     * 递归查询父类名称方法
     *
     * @param name
     * @param entity
     * @return
     */
    public String recursionDocs(String name, SysDocumentDocsubcategoryEntity entity) {
        if (entity != null && entity.getMaincategoryId() != null) {
            String name01 = "";
            SysDocumentDocsubcategoryEntity byId = sysDocumentDocsubcategoryService.getById(entity.getMaincategoryId());

            if (byId != null) {
                name01 = byId.getCategoryname() + "/" + name;
            }
            if (entity.getMaincategoryId() != 0) {
                return recursionDocs(name01, byId);
            } else {
                return name;
            }

        } else {
            return name;
        }
    }

    /**
     * 查询这个用户权限里面的 分别--角色---人力资源 ---部门
     *
     * @param userid
     * @return
     */
    public List<Long> filtRationList(Long userid) {

        List<Long> longList = new ArrayList();//保存数据
        List<SysDocshareEntity> list1 = sysDocshareService.list();
        for (SysDocshareEntity entity : list1) {
            //共享类型(1人力资源，2部门，3角色，4所有人)
            if (entity.getSharetype() == 1) {
                if (entity.getUserid() == userid) {
                    longList.add(entity.getDocid());
                }
            } else if (entity.getSharetype() == 2) {
                //根据所在部门查人员
                List<Long> user = sysUserService.queryDeptRoleListPage(entity.getDepartmentid(), "dept_id");

                for (Long u : user) {
                    if (u == userid) {
                        longList.add(entity.getDocid());
                    }
                }


            } else if (entity.getSharetype() == 3) {
                //根据角色查人员
                List<Long> user = sysUserService.queryDeptRoleListPage(entity.getRoleid(), "role_id");

                for (Long u : user) {
                    if (u == userid) {
                        longList.add(entity.getDocid());
                    }
                }


            }
        }
        return longList;
    }

}
